/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
#!/usr/bin/python
# -*- coding: utf-8 -*-
# To fetch images

import sys, time, ctypes
sys.path.append("../../../../GIMI/wrap/Python/lib/")
sys.path.append("../../../interfaces/wrap/Python/lib/")
import gimi
import ImageClient as IC

def parseArgs(args):
	parsedArgs = {}
	nextIsValueOf = ""
	for arg in args:
		if arg[0] == '-':
			nextIsValueOf = arg[1:]
			parsedArgs[nextIsValueOf] = ""
		else:
			if nextIsValueOf != "":
				parsedArgs[nextIsValueOf] = arg
				nextIsValueOf = ""
	return parsedArgs



def printUsage():
	print """
This is imageclient example to fetch image trough MaCI interface
 
Usage is:	%s [OPTIONS]
  [-u addr]			Use 'addr' as GIMnet AccessPoints address
  [-p port]			Use 'port' as GIMnet AccessPoints port
  [-n name]			Use 'name' as this nodes GIMnet name
  [-G name]			Specify the MaCIGroup of ImageClient
  [-I name]			Specify the Instance name for ImageClient
  
  [-h]				print this
  [-f name]			filename to save image (default img)
	"""%sys.argv[0]


g = gimi.GIMI()
ic = IC.CImageClient(g, 0)

name = "pyExampleImageClient"
groupName = "Rolloottori"
instanceName = "sony"
server = "130.233.120.103"
port = 50006
filename = "img"

if len(sys.argv) < 4:
	printUsage()


#get command line options
args = parseArgs(sys.argv)

if args.has_key("h"):
	printUsage()
	sys.exit()
if args.has_key("u"):server = args['u']
if args.has_key("p"):port = int(args['p'])
if args.has_key("n"):name = args['n']
if args.has_key("G"):groupName = args['G']
if args.has_key("I"):instanceName = args['I']
if args.has_key("f"):filename = args['f']


#make connection
print "connecting to %s:%s as %s..."%(server, port, name),
ret = g.connectToHubEx(server, port, name)
if ret != IC.KMaCIOK:
	print "Failed: ", IC.GetErrorStr(ret)
	sys.exit()
else: print IC.GetErrorStr(ret)

print "set target"
target = "%s.MaCI_Image.%s"%(groupName, instanceName)
ic.SetDefaultTarget(IC.SMaCISL(target))

print "open...",
ret = ic.Open()
if ret != IC.KMaCIOK:
	print "Failed: ", IC.GetErrorStr(ret)
	sys.exit()
else: print IC.GetErrorStr(ret)

#get image
imageD = IC.CImageData()
imageC = IC.CImageContainer()
imageD_seq = 0
bImage = False
try:
	while not bImage:
		print "receiving data... ",
		ret = ic.GetImageData(imageD, imageD_seq, 1000)
		print ret
		if ret[0]:
			print "put image to container... ",
			bImage = imageD.GetImage(imageC, None, False)
			print bImage
			if bImage:
				if imageC.GetImageInfoRef().imagedatatype == IC.KImageDataJPEG: filename += ".jpg"
				elif imageC.GetImageInfoRef().imagedatatype == IC.KImageDataRGB: filename += ".rgb"
				elif imageC.GetImageInfoRef().imagedatatype == IC.KImageDataPNG: filename += ".png"
				else: filename += ".raw"
		
				f = open('RAW'+filename, 'wb')
				ptr = imageC.GetImageDataPtr()
				size = imageC.GetImageDataSize()
				d = ""
				s = 0
				image = imageC.GetImageDataPtr2(d)
				print filename
				print size
				print ptr
				print image[:10]
				print "\nwriting buffer to file"
				f.write(image[:size])
				f.close()
				print "writing to file"
				imageC.WriteImageToFile(filename)
				# Convert to JPEG and write again (only if wasn't JPEG already)
				if imageC.GetImageInfoRef().imagedatatype != IC.KImageDataJPEG:
					# Convert to JPEG!
					if imageC.ConvertTo(IC.KImageDataJPEG):
						print "converted to jpeg*"
				print "done"
			else:
				print "Received data did not contain any images"
		else:
			print "GetImageData timed out"

except KeyboardInterrupt:
	print "moi moi"
print "Closing...",
ic.Close()
print "closed"
